//
//  SplashViewController.m
//  YaoChenPz
//
//  Created by 刘炳举 on 8/16/15.
//  Copyright (c) 2015 com.lbj.org. All rights reserved.
//

#import "SplashViewController.h"
#import "ViewController.h"
#import "tools.h"
#define  shURL  @"http://web.juhe.cn:8080/finance/stock/shall?key=52fe8c4ff3f902f49e4d4d9148e841fd"
#define  szURL  @"http://web.juhe.cn:8080/finance/stock/szall?key=52fe8c4ff3f902f49e4d4d9148e841fd"
#define  GETSHARESINFO 0
#define  GETSHARESCOUNT 1
#define  FLASHSHARESCOUNT 2
@interface SplashViewController (){
    int totalCount;
    int page;
    NSString* shUrl;
    NSString* szUrl;
    BOOL isSh;
    BOOL isSz;
    NSMutableArray *shArray ;
    NSMutableArray *szArray ;
    NSString* filePath;
    NSMutableArray *allSharesCountFormFile;
}

@end

@implementation SplashViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initTitleBar];
    page = 1;
    totalCount = 0;
    shUrl = [[NSString alloc] initWithFormat:@"%@&page=%d",shURL,page];
    szUrl = [[NSString alloc] initWithFormat:@"%@&page=%d",szURL,page];

    shArray = [[NSMutableArray alloc] init];
    szArray = [[NSMutableArray alloc] init];
    //获得本地文件中所有股票数量
    filePath = [tools returnPlistPath];
    allSharesCountFormFile = [NSMutableArray arrayWithContentsOfFile:filePath];
    
    //获取网络上所有股票数量
    [self getSharesCountFromWeb:shURL type:FLASHSHARESCOUNT];
    
    [self getSharesCountFromWeb:szURL type:FLASHSHARESCOUNT];
    //判断从而更新本地数据
    if (!([allSharesCountFormFile count] == totalCount)) {
        [self getSharesCount:shURL type:GETSHARESCOUNT];
    
        [self getSharesCount:szURL type:GETSHARESCOUNT];
        
        [shArray addObjectsFromArray:szArray];
        [shArray writeToFile:filePath atomically:YES];
    }

    ViewController *toCtrler = [self.storyboard instantiateViewControllerWithIdentifier:@"LoginView"];
    [self.navigationController pushViewController:toCtrler animated:NO];
}

-(void)request:(NSString*)url type:(int)type page:(int) cPage{
   // NSLog(@"curPage:%d",cPage);
    NSString* cUrl = [[NSString alloc] initWithFormat:@"%@&page=%d",url,cPage];
    NSURL *SHurl = [NSURL URLWithString:cUrl];
    // 3.创建网络请求
    NSURLRequest *request = [NSURLRequest requestWithURL:SHurl cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    // 创建同步链接

    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (data) {
        switch (type) {
            case GETSHARESCOUNT:
                [self returnSharesCount:data url:url ];
                break;
            case GETSHARESINFO:
                [self getAllShares:data url:url];
                break;
            case FLASHSHARESCOUNT:
                [self returnSharesTotalCount:data url:url];
                break;
            default:
                break;
        }
    }
}

-(void)getAllShares:(NSData*)data url:(NSString*)url{
    NSDictionary* dic = [tools JSonData:data];
    NSArray* infoDic =[[dic objectForKey:@"result"] objectForKey:@"data"];
    if (infoDic == nil) return ;
    
    if([url isEqualToString:shURL]){
        for (int i =0; i < [infoDic count]; i++) {
            NSString* codeStr = [NSString stringWithFormat:@"%@ %@", [[infoDic objectAtIndex:i] objectForKey:@"code"],[tools replaceUnicode:[[infoDic objectAtIndex:i] objectForKey:@"name"]] ];
            [shArray addObject:codeStr];
        }
    }else if([url isEqualToString:szURL]){
        for (int i =0; i < [infoDic count]; i++) {
            NSString* codeStr = [NSString stringWithFormat:@"%@ %@", [[infoDic objectAtIndex:i] objectForKey:@"code"],[tools replaceUnicode:[[infoDic objectAtIndex:i] objectForKey:@"name"]] ];
            [szArray addObject:codeStr];
        }
    }
    
}

-(void)getSharesCount:(NSString*)url type:(int)type{
    [self request:url type:type page:1];
}

-(void)returnSharesCount:(NSData*)data url:(NSString*)url{
    
    NSDictionary* dic = [tools JSonData:data];
    
    int intSt = [[NSString stringWithFormat:@"%@",[[dic objectForKey:@"result"] objectForKey:@"totalCount"]] intValue];
    if (intSt % 20 == 0) {
        intSt = intSt/20 ;
    }else{
        intSt = intSt/20 +1;
    }
    for (int i =1; i <intSt+1; i++) {
        [self request:url type:GETSHARESINFO page:i];
    }
}

-(void)returnSharesTotalCount:data url:url{
    NSDictionary* dic = [tools JSonData:data];
    
    int intSt = [[NSString stringWithFormat:@"%@",[[dic objectForKey:@"result"] objectForKey:@"totalCount"]] intValue];
    totalCount = totalCount + intSt;
}
-(void)getSharesCountFromWeb:(NSString*)url type:(int)type{
    [self request:url type:type page:1];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)initTitleBar {
    UIBarButtonItem *btnBack = [[UIBarButtonItem alloc]
                                initWithTitle:@""
                                style:UIBarButtonItemStylePlain
                                target:self
                                action:nil];
    self.navigationController.navigationBar.topItem.backBarButtonItem=btnBack;
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
